﻿using System.Windows;
using System.Windows.Interop;

namespace SerialPortDebugTool
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //Windows消息编号 16进制
        public const int WM_DEVICECHANGE = 0x219;          
        public const int DBT_DEVICEARRIVAL = 0x8000;
        public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;

        private readonly MainWindowViewModel _viewModel;

        public MainWindow()
        {
            InitializeComponent();
            _viewModel = new MainWindowViewModel();
            this.DataContext = _viewModel;
        }

        /// <summary>
        /// 窗体资源初始化加载完后触发
        /// </summary>
        /// <param name="e"></param>
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
            if (source != null)
            {
                IntPtr windowHandle = source.Handle;
                source?.AddHook(new HwndSourceHook(WndProc));
            }
        }

        /// <summary>
        /// 设备热插拔钩子
        /// </summary>
        /// <returns></returns>
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_DEVICECHANGE)
            {
                switch (wParam.ToInt32())
                {
                    case DBT_DEVICEARRIVAL://设备插入  
                        
                        break;
                    case DBT_DEVICEREMOVECOMPLETE: //设备卸载
                        
                        break;
                    default:
                        break;
                }
            }
            return IntPtr.Zero;
        }
    }
}